package com.apply.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.apply.dao.UserDao;
import com.apply.entity.User;
import com.apply.entity.teachers;


@Controller
public class FileUpload {
	
	@Autowired
	private UserDao userDao;
	
	@RequestMapping(value="/fileupload")
	@ResponseBody
	public void fileUpload(HttpServletRequest request, HttpServletResponse response){

		Integer chunk = null; /* 分割块数 */
		Integer chunks = null; /* 总分割数 */
		String tempFileName = null; /* 临时文件�?*/
		String newFileName = null; /* �?��合并后的新文件名 */
		String name =null;//原来的文件名
		BufferedOutputStream	outputStream	= null;
		
		
		ServletContext sctx = request.getServletContext();
		String uploadPath = sctx.getRealPath("statics/upload");
		
		   
		 

			try {
				DiskFileItemFactory factory = new DiskFileItemFactory();
				factory.setSizeThreshold( 1024 );
				/* factory.setRepository(new File(repositoryPath));// 设置临时目录 */
				ServletFileUpload upload = new ServletFileUpload( factory );
				upload.setHeaderEncoding( "UTF-8" );
				/* upload.setSizeMax(5 * 1024 * 1024);// 设置附件�?��大小，超过这个大小上传会不成�?*/
				List<FileItem> items = upload.parseRequest( request );
				for ( FileItem item : items )
				{
					if ( item.isFormField() ) /* 是文本域 */
					{
						if ( item.getFieldName().equals( "name" ) )
						{
							tempFileName = item.getString();
							/* System.out.println("临时文件名：" + tempFileName); */
						} else if ( item.getFieldName().equals( "chunk" ) )
						{
							chunk = Integer.parseInt( item.getString() );
							/* System.out.println("当前文件块：" + (chunk + 1)); */
						} else if ( item.getFieldName().equals( "chunks" ) )
						{
							chunks = Integer.parseInt( item.getString() );
							/* System.out.println("文件总分块：" + chunks); */
						}
					} else { /* 如果是文件类�?*/
						name=item.getName();
						if ( tempFileName != null )
						{
							String chunkName = tempFileName;
							if ( chunk != null )
							{
								chunkName = chunk + "_" + tempFileName;
							}
							File savedFile = new File( uploadPath, chunkName );
							item.write( savedFile );
						}
					}
				}

				newFileName = UUID.randomUUID().toString().replace( "-", "" )
					      .concat( "." )
					      .concat( FilenameUtils.getExtension( tempFileName ) );
				if ( chunk != null && chunk + 1 == chunks )
				{
					outputStream = new BufferedOutputStream(
						new FileOutputStream( new File( uploadPath, newFileName ) ) );
					/* 遍历文件合并 */
					for ( int i = 0; i < chunks; i++ )
					{
						File tempFile = new File( uploadPath, i + "_" + tempFileName );
						byte[] bytes = FileUtils.readFileToByteArray( tempFile );
						outputStream.write( bytes );
						outputStream.flush();
						tempFile.delete();
					}
					outputStream.flush();
				}
				
				Map<String, Object> m = new HashMap<String, Object>();
				m.put( "status", true );
				m.put( "fileUrl","/apply/statics/upload/"+newFileName );
				m.put("name", name);
				
				User user =(User) request.getSession().getAttribute("user");
				user.setHeadimg("/apply/statics/upload/"+newFileName);
				userDao.setUser(user);
				
				
				response.getWriter().write( JSON.toJSONString( m ) );
			} catch ( FileUploadException e ) {
				
				e.printStackTrace();
				Map<String, Object> m = new HashMap<String, Object>();
				m.put( "status", false );
				try {
					response.getWriter().write( JSON.toJSONString( m ) );
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			
			} catch ( Exception e ) {
				e.printStackTrace();
				Map<String, Object> m = new HashMap<String, Object>();
				m.put( "status", false );
				
				try {
					response.getWriter().write( JSON.toJSONString( m ) );
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			
			
			} finally {
				try {
					if ( outputStream != null )
						outputStream.close();
				} catch ( IOException e ) {
					e.printStackTrace();
				}
			}
		
	
	
		
		
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	@RequestMapping(value="/XSLupload")
	@ResponseBody
	public void XSLUpload(HttpServletRequest request, HttpServletResponse response){

		
		System.out.println("aaaaaaaa");
		Integer chunk = null; /* 分割块数 */
		Integer chunks = null; /* 总分割数 */
		String tempFileName = null; /* 临时文件�?*/
		String newFileName = null; /* �?��合并后的新文件名 */
		String name =null;//原来的文件名
		BufferedOutputStream	outputStream	= null;
		
		
		ServletContext sctx = request.getServletContext();
		String uploadPath = sctx.getRealPath("statics/upload");
		
		   
		 

			try {
				DiskFileItemFactory factory = new DiskFileItemFactory();
				factory.setSizeThreshold( 1024 );
				/* factory.setRepository(new File(repositoryPath));// 设置临时目录 */
				ServletFileUpload upload = new ServletFileUpload( factory );
				upload.setHeaderEncoding( "UTF-8" );
				/* upload.setSizeMax(5 * 1024 * 1024);// 设置附件�?��大小，超过这个大小上传会不成�?*/
				List<FileItem> items = upload.parseRequest( request );
				for ( FileItem item : items )
				{
					if ( item.isFormField() ) /* 是文本域 */
					{
						if ( item.getFieldName().equals( "name" ) )
						{
							tempFileName = item.getString();
							/* System.out.println("临时文件名：" + tempFileName); */
						} else if ( item.getFieldName().equals( "chunk" ) )
						{
							chunk = Integer.parseInt( item.getString() );
							/* System.out.println("当前文件块：" + (chunk + 1)); */
						} else if ( item.getFieldName().equals( "chunks" ) )
						{
							chunks = Integer.parseInt( item.getString() );
							/* System.out.println("文件总分块：" + chunks); */
						}
					} else { /* 如果是文件类�?*/
						name=item.getName();
						if ( tempFileName != null )
						{
							String chunkName = tempFileName;
							if ( chunk != null )
							{
								chunkName = chunk + "_" + tempFileName;
							}
							File savedFile = new File( uploadPath, chunkName );
							item.write( savedFile );
						}
					}
				}

				newFileName = UUID.randomUUID().toString().replace( "-", "" )
					      .concat( "." )
					      .concat( FilenameUtils.getExtension( tempFileName ) );
				if ( chunk != null && chunk + 1 == chunks )
				{
					outputStream = new BufferedOutputStream(
						new FileOutputStream( new File( uploadPath, newFileName ) ) );
					/* 遍历文件合并 */
					for ( int i = 0; i < chunks; i++ )
					{
						File tempFile = new File( uploadPath, i + "_" + tempFileName );
						byte[] bytes = FileUtils.readFileToByteArray( tempFile );
						outputStream.write( bytes );
						outputStream.flush();
						tempFile.delete();
					}
					outputStream.flush();
				}
				
				Map<String, Object> m = new HashMap<String, Object>();
				m.put( "status", true );
				m.put( "fileUrl","/apply/statics/upload/"+newFileName );
				m.put( "name", name);
				
				String path = "/statics/upload/"+newFileName;
				JXXSL(request.getSession().getServletContext().getRealPath(path) );
				response.getWriter().write( JSON.toJSONString( m ) );
			} catch ( FileUploadException e ) {
				
				e.printStackTrace();
				Map<String, Object> m = new HashMap<String, Object>();
				m.put( "status", false );
				try {
					response.getWriter().write( JSON.toJSONString( m ) );
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			
			} catch ( Exception e ) {
				e.printStackTrace();
				Map<String, Object> m = new HashMap<String, Object>();
				m.put( "status", false );
				
				try {
					response.getWriter().write( JSON.toJSONString( m ) );
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			
			
			} finally {
				try {
					if ( outputStream != null )
						outputStream.close();
				} catch ( IOException e ) {
					e.printStackTrace();
				}
			}
		
	
	
		
		
	}
	
	
	
	
	
	/**
	 * 解析XSL文件
	 * @param path
	 */
	public  void JXXSL(String path)  
	  
    {   
  
        jxl.Workbook readwb = null;   
  
        try    
  
        {   
  
            //构建Workbook对象, 只读Workbook对象   
  
            //直接从本地文件创建Workbook   
  
            InputStream instream = new FileInputStream(path);   
            
           
            readwb = Workbook.getWorkbook(instream);   
  
    
  
            //Sheet的下标是从0开始   
  
            //获取第一张Sheet表   
  
            Sheet readsheet = readwb.getSheet(0);   
  
            //获取Sheet表中所包含的总列数   
  
            int rsColumns = readsheet.getColumns();   
  
            //获取Sheet表中所包含的总行数   
  
            int rsRows = readsheet.getRows();   
  
            //获取指定单元格的对象引用   
            
            List<teachers> list = new ArrayList<teachers>();
            for (int i = 0; i < rsRows; i++)   
  
            {   
            	
            	 if(i>0){
  
            	teachers t = new teachers();
                for (int j = 0; j < rsColumns; j++)   
  
                {   
  
                    Cell cell = readsheet.getCell(j, i);   
                    
                   
                    	switch (j) {
						case 0:
							t.setTeachername(cell.getContents());
							break;
						case 1:
							t.setSex(cell.getContents());
							break;
							
						case 2:
							t.setPhone(cell.getContents());
							break;	
							
						case 3:
							t.setEntrytime(cell.getContents());
							break;
							
						case 4:
							t.setInfo(cell.getContents());
							break;
							
						case 5:
							t.setPositionid(Integer.parseInt(cell.getContents()));
							break;
							
						case 6:
							t.setDepartmentid(Integer.parseInt(cell.getContents()));
							break;
						case 7:
							t.setCampusid(Integer.parseInt(cell.getContents()));
							break;
							
						default:
							break;
						}
                    	
                   
                   
                   
                   
                }   
                
                
                list.add(t);
                
            	 }
            }   
  
            System.out.println(list.toString());
            
  
        } catch (Exception e) {   
  
            e.printStackTrace();   
  
        } finally {   
  
            readwb.close();   
  
        }   
  
}   
	
	
	
	
	
	
	
	

}
